from flask import Flask
import json
from flask import request
from flask_sqlalchemy import SQLAlchemy
import util
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app, use_native_unicode='utf8')
from old import Old

#没用但得留着
@app.route('/user/info', methods=['get'])
def userInfo():
    return json.dumps({
        "avatar": "https://randy168.com/1533262153771.gif",
        "name": "admin",
        "roles": ["admin"],
        "data": ["index","order-manage","order-list","product-manage","product-list","review-manage","return-goods",
                 "goods","goods-list","goods-classify","permission","user-manage","role-manage","menu-manage"]
    })

# 返回老年人信息列表
@app.route('/old', methods=['get'])
def getOld():
    olds = Old.query.all()
    print(olds)
    oldList = []
    for old in olds:
        oldList.append(util.OldToDict(old))
    print(oldList)
    return json.dumps(oldList)

# 返回单一老年人信息（通过id）
@app.route('/old/<id>', methods=['get'])
def getOldById(id):
    #通过id搜索数据库
    old = util.OldToDict(Old.query.get(id))
    return json.dumps([old])

# 更新/增加单一老年人信息
@app.route('/old', methods=['post'])
def UpdateOld():
    data = request.get_json()  #格式 {'id': 169, 'name': '逄无敌', 'mobile': '18680343705', 'address': '536', 'email': '54@qq.com', 'gender': '女', 'age': '542'}
    sqlData = util.dictToOldDic(data)
    #是否存在
    if db.session.query(Old).filter(Old.ID==data['id']).count()!=0:
        user_obj = db.session.query(Old).filter(Old.ID == data['id']).update(sqlData)
        db.session.commit()
    else:
        writeData = util.OldToDict(data).drop('ID')
        db.session.execute(
            Old.__table__.insert(),
            writeData
        )
        db.session.commit()
    return json.dumps([data])

#管理员
@app.route('/admin', methods=['get'])
def getAdmin():
    return json.dumps([{},{}])
@app.route('/admin/<id>', methods=['get'])
def getAdminById(id):
    return json.dumps([{}])
@app.route('/admin', methods=['post'])
def updateAdmin():
    data = request.get_json()
    return json.dumps([{}])

#义工
@app.route('/volunteer', methods=['get'])
def getVolunteer():
    return json.dumps([{},{}])
@app.route('/volunteers/<id>', methods=['get'])
def getVolunteerById(id):
    return json.dumps([{}])
@app.route('/volunteers', methods=['post'])
def updateVolunteer():
    data = request.get_json()
    return json.dumps([{}])

if __name__ == '__main__':
    app.run()
